package com.example.hp.storeapp.fragment;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.hp.storeapp.Const;
import com.example.hp.storeapp.R;
import com.example.hp.storeapp.adapter.ShopListAdapter;
import com.example.hp.storeapp.base.BaseFragment;
import com.example.hp.storeapp.bean.ShopResult;
import com.example.hp.storeapp.interf.RetrofitService;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * A simple {@link Fragment} subclass.
 */
public class ShopListFragment extends BaseFragment{

    private RecyclerView recyclerView;
    private ShopListAdapter adapter;
    // public ShopListAdapter


    public ShopListFragment() {
        // Required empty public constructor
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        //Retrofit请求数据-》显示数据
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Const.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RetrofitService retrofitService =
                retrofit.create(RetrofitService.class);
        Call<List<ShopResult>> call = retrofitService.getAllShops();
        call.enqueue(new Callback<List<ShopResult>>() {
            @Override
            public void onResponse(Call<List<ShopResult>> call, Response<List<ShopResult>> response) {
                if (getActivity() != null){
                    adapter = new ShopListAdapter(getActivity(),response.body());
                    LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
                    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

                    recyclerView.setLayoutManager(layoutManager);
                    recyclerView.setAdapter(adapter);
                    recyclerView.setItemAnimator(new DefaultItemAnimator());
                }

            }

            @Override
            public void onFailure(Call<List<ShopResult>> call, Throwable t) {

            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_shop_list, container, false);
    }

}
